##################################################################
# File : /lua/ui/netork/DSdatabase.lua
# Description : Lua wrapper for the python database
# Author : Neruz
##################################################################

Database = Class(LuaClass) {
	OnCreate = function(self, spec)
		self._path = spec['path']
		SetFrontEndData('DatabaseData', {})
		self:ForkThread(self._GetData)
		GpgNetSend('exec', 'global database', 'database = Base("' .. self._path .. '")')
		self:create{keys = {'username', 'password'}, mode = 'open'}
		GpgNetSend('exec', 'for entry in database:', '	returnData(addr, entry)')
		self._entries = {}
	end,
	
	CheckLogin = function(self, username, password)
		for k, entry in self._entries do
			if entry['username'] == username and entry['password'] == password then
				return true
			end
		end
		return false
	end,
	
	DataReceived = function(self, data)
		if data[1] == "DatabaseData" then
			table.insert(self._entries, dostring(data[2]))
		end
		return true
	end,
	
	create = function(self, args)
		local keys = '"' .. ('", "'):join(args['keys']) .. '"'
		GpgNetSend('exec', 'database.create(' .. keys .. ', mode = "' .. (args['mode'] or 'open') .. '")')
	end,
	
	open = function(self)
		self._entries = {}
		GpgNetSend('exec', 'database.open()')
		GpgNetSend('exec', 'for entry in database:', '	returnData(addr, entry)')
	end,
	
	insert = function(self, args)
		local strKeys = repr(args)
		local sKeys = string.sub(strKeys, 2, strKeys:len() - 1)
		GpgNetSend('exec', 'curInsert = database.insert(' .. sKeys .. ')', 'returnData(addr, database[curInsert])')
	end,
	
	update = function(self, args)
		local strKeys = repr(args['keys'])
		local sKeys = string.sub(strKeys, 2, strKeys:len() - 1)
 		GpgNetSend('exec', 'database.update(database[' .. args['record'] .. '], ' .. sKeys .. ')')
 		for key, val in args['keys'] do
 			self._entries[args['record']][key] = val
 		end
	end,
	
	delete = function(self, records)
		local strRecords = repr(records)
		local sRecords = string.sub(strRecords, 2, strRecords:len() - 1)
		GpgNetSend('exec', 'database.delete([r for r in database if r["__id__"] in [' .. sRecords .. ']])')
		for k, record in records do
			table.removeByKey(self._entries, record)
		end
	end,
	
	commit = function(self)
		GpgNetSend('exec', 'database.commit()')
	end,
	
	_GetData = function(self)
		while true do
			local dataTbl = GetFrontEndData('DatabaseData')
			if not table.empty(dataTbl) then
				for i, data in dataTbl do
					local isProcessed = self:DataReceived(data)
					if isProcessed then
						dataTbl[i] = nil
					end
				end
				SetFrontEndData('DatabaseData', dataTbl)
			end
			WaitSeconds(0.01)
		end
	end,
}